package com.yobol.jgrowth.controller;

import com.yobol.jgrowth.util.Command;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Coding Controller
 *
 * @author yobol
 * @create 2018-04-04 13:05
 **/

@Controller
public class CodingController {

    @RequestMapping(value = "/coding",method = {RequestMethod.POST})
    public String coding(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "code")String code) throws UnsupportedEncodingException {
        String redirectUrl = "/coding";

        Command command = new Command();
        String name = code.substring(code.indexOf("class") + 5).trim().split(" ")[0];
        if (name.contains("{")){
            name = name.split("\\{")[0];
        }
        String cmd = "cmd.exe /c javac D://" + name + ".java & java -classpath D:// " + name;
        Map<String,String> map = command.exec("D://",name + ".java",code,cmd);
        cmd = "cmd.exe /c del D:\\" + name + ".java & del D:\\" + name + ".class";
        command.exec(cmd);

        request.getSession().setAttribute("code",code.trim());
        request.getSession().setAttribute("coding_out",map.get("out"));
        request.getSession().setAttribute("coding_error",map.get("error"));
        return "redirect:" + redirectUrl;
    }
}
